uniform vec4 lightPosition;
uniform sampler2D hftex;
uniform sampler2D ntex;
uniform int size;

const float externalIndex = 1.0003;
const float internalIndex = 1.33;
const float zBottom = -0.2;

void myRefract(in vec3 incident, in vec3 normal,
			   out vec3 refraction, out float transmittance)
{
	float eta = externalIndex / internalIndex;
	float cos_theta1 = abs(dot(incident, normal));
	float cos_theta2 = sqrt(1.0 - eta * eta * (1.0 - cos_theta1 * cos_theta1));
	refraction = incident * eta - normal * (cos_theta2 - eta * cos_theta1);

	float fresnel_rs = (internalIndex * cos_theta2 - externalIndex * cos_theta1) /
					   (internalIndex * cos_theta2 + externalIndex * cos_theta1);

	float fresnel_rp = (internalIndex * cos_theta1 - externalIndex * cos_theta2) /
					   (internalIndex * cos_theta1 + externalIndex * cos_theta2);

	transmittance = 1.0 - (fresnel_rs * fresnel_rs + fresnel_rp * fresnel_rp) * 0.5;
}

void main(void)
{
	vec3 vertex = vec3(texture2D(hftex, gl_TexCoord[0].st));
	vec3 normal = vec3(texture2D(ntex, gl_TexCoord[0].st));

	vec3 lightVec = normalize(vertex - vec3(lightPosition));
	vec3 waterRefract;
	float waterTrans;
	myRefract(lightVec, normal, waterRefract, waterTrans);
	vec2 caustics;
	caustics.s = vertex.x + (zBottom - vertex.z) * waterRefract.x / waterRefract.z;
	caustics.t = vertex.y + (zBottom - vertex.z) * waterRefract.y / waterRefract.z;

	gl_FragColor = vec4(caustics.s, caustics.t, -0.2, 1.0);
}